package com.itheima.service.impl;

import com.itheima.common.utils.ValidateCodeUtils;
import com.itheima.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送手机验证码
     * @param telephone
     * @return
     */
    @Override
    public Boolean sendValidateCode4Phone(String telephone){
        // TODO 发送短信验证码，暂时无法实现
        String validateCode = VCodeGenerator(telephone);
        if (validateCode != null){
            log.info("发送验证码成功，验证码为：{}", validateCode);
            return true;
        }else {
            log.info("发送验证码失败");
            return false;
        }
    }

    /**
     * 验证码生成器
     * @return
     */
    @Override
    public String VCodeGenerator(String telephone){
        String validateCode = ValidateCodeUtils.generateValidateCode4String(4);
        log.info("生成的验证码为：{}", validateCode);
        ValueOperations<String, String> VCodeOps = redisTemplate.opsForValue();
        VCodeOps.set("validateCode:" + telephone, validateCode, 1, TimeUnit.MINUTES);
        return validateCode;
    }
}
